package com.zhouheng.springbootmultithreading.tuling.jmm.success;

import java.util.concurrent.locks.LockSupport;

/**
 *
 * 发放许可
 * LockSupport.unpark(Thread.currentThread());
 *
 * 也会调用lock 前缀指令
 */
public class VisibilitySuccessTest5 {

    private boolean flag = true;
    private int count = 0;

    public void refresh() {
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag:" + flag);
    }

    public void load() {
        System.out.println(Thread.currentThread().getName() + "开始执行.....");
        while (flag) {
            //TODO  业务逻辑
            count++;
            //
            LockSupport.unpark(Thread.currentThread());
        }
        System.out.println(Thread.currentThread().getName() + "跳出循环: count=" + count);
    }

    public static void main(String[] args) throws InterruptedException {
        VisibilitySuccessTest5 test = new VisibilitySuccessTest5();

        // 线程threadA模拟数据加载场景
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        // 让threadA执行一会儿
        Thread.sleep(1000);
        // 线程threadB通过flag控制threadA的执行时间
        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();
    }

}
